package jinyilw.swing.visuals.comp;

import jinyilw.swing.ComponentTools;
import jinyilw.common.Operator;

import javax.swing.Icon;
import java.awt.Composite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ActIconComp extends MouseActComp
{
	private static final long serialVersionUID = -1276675463020135887L;
	private Icon icon, overIcon;

	public ActIconComp()
	{
		enableMouseAct();
	}

	public ActIconComp(Icon icon, Icon overIcon)
	{
		this();
		setActionIcon(icon, overIcon);
	}

	public void setIcon(Icon icon)
	{
		setActionIcon(icon, icon);
	}

	//	public void setResActionIcon(String iconPath, String oicPath)
	//	{
	//		setActionIcon(ResourceManager.getResLazyScaleIcon(iconPath),
	//				ResourceManager.getResLazyScaleIcon(oicPath));
	//	}

	public void setActionIcon(Icon icon, Icon overIcon)
	{
		this.icon = icon;
		this.overIcon = overIcon;
		if (icon != null)
		{
			int w = icon.getIconWidth(), h = icon.getIconHeight();
			if (w != getWidth() || h != getHeight())
			{
				setSize(w, h);
				return;
			}
		}
		if (isShowing())
			repaint();
	}

	public void addDoubleClickOperator(final Operator<MouseEvent> operator)
	{
		addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				if (isEnabled() && e.getClickCount() == 2)
					operator.operate(e);
			}
		});
	}

	@Override
	public void paint(Graphics g)
	{
		Icon ico = isRollover ? overIcon : icon;
		if (ico != null)
		{
			boolean isEnabled = isEnabled();
			Graphics2D g2d = (Graphics2D) g;
			Composite composite = ComponentTools.applyEnableAlpha(g2d,
					isEnabled, 1f, 0.3f);
			if (isEnabled && isPressed)
				g2d.translate(0.5, 0.5);
			ico.paintIcon(this, g2d, 0, 0);
			if (isEnabled && isPressed)
				g2d.translate(-0.5, -0.5);
			if (composite != null)
				g2d.setComposite(composite);
		}
	}
}
